import { createStore } from 'vuex';
import {adminLoginApi, getUserMsgApi, logoutApi} from '../api/request/user';

export interface CurrentUser {
  user: string;
  route: UserRoute[] | [];
}
export interface UserRoute {
  id: number;
  path: string;
  title: string | undefined;
  children: UserRoute[] | [];
}

export interface StateType {
  currentUser: CurrentUser;
  option: any;
}
const initState: StateType = {
  currentUser: {
    user: '',
    route: []
  },
  option: {}
};
export default createStore({
  state: {
    ...initState
  },
  /**
   mutations方法书写的时候命名最后都加上Mutation，方便代码中辨认
   */
  mutations: {
    saveCurrentUserMutation(state, payload) {
      state.currentUser = {
        ...initState.currentUser,
        ...payload
      };
    }
  },
  /**
   actions方法书写的时候命名最后都加上Action，方便代码中辨认
   */
  actions: {
    async loginAction({ commit }, parm) {
      try {
        const data: any = await adminLoginApi(parm);
        commit('saveCurrentUserMutation', data || {});
        return true;
      } catch (error) {
        return false;
      }
    },
    async getUserMsgAction({ commit }) {
      try {
        const data: any = await getUserMsgApi();
        commit('saveCurrentUserMutation', data || {});
        return true;
      } catch (error) {
        return false;
      }
    },
    async logoutAction({ commit }) {
      try {
        const data: any = await logoutApi();
        commit('saveCurrentUserMutation', {
          user: '',
          route: []
        });
        return true;
      } catch (error) {
        return false;
      }
    }
  },
  modules: {}
});
